<template>
  <view class="login-container">
    <!-- 顶部背景 -->
    <view class="header">
      <view class="title">登录</view>
      <view class="subtitle">欢迎回来</view>
    </view>

    <!-- 已登录状态显示用户信息 -->
    <view class="user-info" v-if="isLoggedIn">
      <image
        class="avatar"
        :src="userInfo.avatar || '/static/images/default-avatar.png'"
        mode="aspectFill"
      ></image>
      <text class="username">{{ userInfo.username || '未设置昵称' }}</text>
      <button class="logout-button" @tap="handleLogout">退出登录</button>
    </view>

    <!-- 未登录状态显示登录表单 -->
    <view class="form-section" v-else>
      <view class="input-group">
        <text class="label">账号</text>
        <input class="input" type="text" v-model="form.account" placeholder="请输入账号" />
      </view>

      <view class="input-group">
        <text class="label">密码</text>
        <input
          class="input"
          type="password"
          v-model="form.password"
          placeholder="请输入密码"
          password
        />
      </view>

      <view class="input-group">
        <text class="label">验证码</text>
        <view class="code-input-group">
          <input
            class="input"
            type="text"
            v-model="form.code"
            placeholder="请输入验证码"
            maxlength="6"
          />
          <image class="captcha-image" :src="captchaUrl" mode="aspectFit" @tap="refreshCaptcha" />
        </view>
      </view>

      <view class="button-group">
        <button
          class="submit-button"
          :disabled="!isFormValid"
          :class="{ disabled: !isFormValid }"
          @click="handleLogin"
        >
          登录
        </button>

        <button class="register-button" @tap="goToRegister">注册账号</button>
      </view>

      <view class="agreement">
        <checkbox
          :checked="form.agreement"
          @tap="form.agreement = !form.agreement"
          color="#9370DB"
        />
        <text class="agreement-text">
          我已阅读并同意
          <text class="link" @tap="showAgreement">《用户协议》</text>
          和
          <text class="link" @tap="showPrivacy">《隐私政策》</text>
        </text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getCaptcha, login } from '@/api/my'

interface LoginForm {
  account: string
  password: string
  code: string
  agreement: boolean
}

const form = ref<LoginForm>({
  account: '',
  password: '',
  code: '',
  agreement: false,
})

const captchaUrl = ref('')

const isFormValid = computed(() => {
  return (
    form.value.account.length >= 1 &&
    form.value.password.length >= 4 &&
    form.value.code.length === 4 &&
    form.value.agreement
  )
})

// 用户信息相关
const userInfo = ref<any>({})
const isLoggedIn = ref(false)

// 检查登录状态
const checkLoginStatus = () => {
  const storedUserInfo = uni.getStorageSync('userInfo')
  if (storedUserInfo) {
    userInfo.value = storedUserInfo
    isLoggedIn.value = true
  } else {
    isLoggedIn.value = false
  }
}

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        uni.removeStorageSync('token')
        uni.removeStorageSync('userInfo')
        isLoggedIn.value = false
        userInfo.value = {}
        // 刷新验证码
        refreshCaptcha()
      }
    },
  })
}

// 获取验证码图片
const refreshCaptcha = async () => {
  try {
    const res = await getCaptcha()
    if (res.statusCode === 200 && res.data) {
      // 将 ArrayBuffer 转换为 Base64
      const arrayBuffer = res.data as ArrayBuffer
      const base64 = uni.arrayBufferToBase64(arrayBuffer)
      // 设置图片 src
      captchaUrl.value = `data:image/png;base64,${base64}`
    } else {
      uni.showToast({
        title: '获取验证码失败',
        icon: 'none',
      })
    }
  } catch (error) {
    uni.showToast({
      title: '获取验证码失败',
      icon: 'none',
    })
  }
}

// 页面加载时获取验证码
onMounted(() => {
  checkLoginStatus()
  if (!isLoggedIn.value) {
    refreshCaptcha()
  }
})

const handleLogin = async () => {
  if (!isFormValid.value) return

  const uuid = uni.getStorageSync('__DC_STAT_UUID')

  uni.showLoading({
    title: '登录中...',
  })

  try {
    const res = await login({
      username: form.value.account,
      password: form.value.password,
      verifyCode: form.value.code,
      uuid,
    })

    if (res.statusCode === 200) {
      const { code, info, data } = res.data as any

      if (code === 200) {
        // 存储token
        if (data.token) {
          uni.setStorageSync('token', data.token)
        }
        // 将用户信息统一存储在userInfo对象中
        const userInfo = {
          id: data.id,
          avatar: data.avatar,
          username: data.username,
        }
        uni.setStorageSync('userInfo', userInfo)

        uni.showToast({
          title: '登录成功',
          icon: 'success',
        })

        setTimeout(() => {
          // 获取页面栈信息
          const pages = getCurrentPages()
          if (pages.length > 1) {
            // 如果有上一页，则返回
            uni.navigateBack()
          } else {
            // 如果没有上一页，则跳转到首页
            uni.reLaunch({
              url: '/pages/index/index',
            })
          }
        }, 1500)
      } else {
        // 如果验证码错误，刷新验证码
        if (info.includes('验证码')) {
          refreshCaptcha()
        }
        uni.showToast({
          title: info || '登录失败',
          icon: 'none',
        })
      }
    } else {
      uni.showToast({
        title: '登录失败',
        icon: 'none',
      })
    }
  } catch (error) {
    uni.showToast({
      title: '登录失败',
      icon: 'none',
    })
  } finally {
    uni.hideLoading()
  }
}

const goToRegister = () => {
  uni.navigateTo({ url: '/pages/register/register' })
}

const showAgreement = () => {
  uni.showToast({
    title: '用户协议',
    icon: 'none',
  })
}

const showPrivacy = () => {
  uni.showToast({
    title: '隐私政策',
    icon: 'none',
  })
}
</script>

<style lang="scss">
// 薰衣草紫主题色
$theme-color: #9370db;
$light-theme-color: #e6e6fa;
$text-color: #ffffff;
$border-color: rgba(255, 255, 255, 0.2);

.login-container {
  min-height: 100vh;
  background: linear-gradient(180deg, $theme-color 0%, $light-theme-color 100%);
  padding: 0;

  .header {
    padding: 60rpx 40rpx 40rpx;

    .title {
      font-size: 48rpx;
      color: #ffffff;
      font-weight: bold;
      margin-bottom: 20rpx;
    }

    .subtitle {
      font-size: 32rpx;
      color: rgba(255, 255, 255, 0.9);
    }
  }

  .form-section {
    padding: 40rpx;

    .input-group {
      margin-bottom: 40rpx;

      .label {
        font-size: 28rpx;
        color: #ffffff;
        margin-bottom: 20rpx;
        display: block;
      }

      .input {
        height: 90rpx;
        background-color: rgba(255, 255, 255, 0.2);
        border-radius: 45rpx;
        padding: 0 40rpx;
        font-size: 28rpx;
        color: #ffffff;

        &::placeholder {
          color: rgba(255, 255, 255, 0.6);
        }
      }

      .code-input-group {
        display: flex;
        align-items: center;
        gap: 20rpx;

        .input {
          flex: 1;
        }

        .captcha-image {
          width: 200rpx;
          height: 90rpx;
          background: rgba(255, 255, 255, 0.3);
          border-radius: 45rpx;
        }
      }
    }

    .button-group {
      margin: 60rpx 0;
      display: flex;
      flex-direction: column;
      gap: 30rpx;

      .submit-button {
        width: 100%;
        height: 90rpx;
        background: #ffffff;
        color: $theme-color;
        border-radius: 45rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        border: none;
        font-weight: bold;

        &.disabled {
          background: rgba(255, 255, 255, 0.5);
          color: rgba(147, 112, 219, 0.5);
        }

        &::after {
          border: none;
        }
      }

      .register-button {
        width: 100%;
        height: 90rpx;
        background: transparent;
        color: #ffffff;
        border: 2rpx solid rgba(255, 255, 255, 0.8);
        border-radius: 45rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;

        &::after {
          border: none;
        }
      }
    }

    .agreement {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10rpx;

      .agreement-text {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.8);
      }

      .link {
        color: #ffffff;
        text-decoration: underline;
      }
    }
  }

  .user-info {
    padding: 60rpx 40rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    .avatar {
      width: 160rpx;
      height: 160rpx;
      border-radius: 50%;
      border: 4rpx solid rgba(255, 255, 255, 0.8);
      margin-bottom: 30rpx;
    }

    .username {
      font-size: 36rpx;
      color: #ffffff;
      margin-bottom: 40rpx;
    }

    .logout-button {
      width: 240rpx;
      height: 80rpx;
      background: rgba(255, 255, 255, 0.2);
      border: 2rpx solid rgba(255, 255, 255, 0.8);
      border-radius: 40rpx;
      color: #ffffff;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      &::after {
        border: none;
      }
    }
  }
}
</style>
